﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using ZOIL.Framework.Core;
using ZOIL.Framework.Presentation;

namespace ZOIL.Library.Behaviors
{
    [Export(typeof(PluginConnectionBehavior))]
    public class MouseConnectionBehavior : PluginConnectionBehavior
    {
        #region private fields

        private IDisposable _mouseConnectionSubscription;

        #endregion

        #region private methods

        private IDisposable RegisterMouseEvents()
        {
            var mouseMove = Observable.FromEventPattern<MouseEventArgs>(AssociatedObject, "MouseMove");

            var mouseLeftButtonDown = Observable.FromEventPattern<MouseButtonEventArgs>(AssociatedObject, "MouseRightButtonDown");

            var mouseLeftButtonUp = Observable.FromEventPattern<MouseButtonEventArgs>(AssociatedObject, "MouseRightButtonUp");

            var mouseMoves = from mm in mouseMove
                             select mm.EventArgs.GetPosition(null);

            var mouseDrag = from mlbd in mouseLeftButtonDown.Select(evt => new Connection(evt.EventArgs.GetPosition(null))).Do(s => { StartConnection(s); Mouse.Capture(AssociatedObject); })
                            from md in mouseMoves.Do(point => mlbd.EndPoint = point).TakeUntil(mouseLeftButtonUp.Do(evt => mlbd.EndPoint = evt.EventArgs.GetPosition(null)).Do(evt => { FinishConnection(mlbd); AssociatedObject.ReleaseMouseCapture(); }))
                            select mlbd;

            return mouseDrag.Subscribe(ChangeConnection);
        }

        #endregion

        #region overrides

        protected override void OnIsEnabledChanged(bool oldIsEnabled, bool newIsEnabled)
        {
            if (newIsEnabled)
            {
                _mouseConnectionSubscription = RegisterMouseEvents();
            }
            else
            {
                if (_mouseConnectionSubscription != null)
                    _mouseConnectionSubscription.Dispose();
            }
        }

        #endregion
    }
}
